import json
from datetime import datetime
from bson import ObjectId
from django.http import JsonResponse
from django.views import View

from apps.talk.models import Spit
from utils.login import loginrequired


# from bs4 import BeautifulSoup
class SpitView(View):
    '''吐槽列表展示'''
    def get(self,request):
        try:
            spits = Spit.objects.all()
            data = []
            for i in spits:
                # 使用ObjectId类将字符串id转换为ObjectId对象
                # aa = collections.fin
                data.append({
                    'id':str(ObjectId(i.id)),
                    'content':i.content,
                    'publishtime':str(i.publishtime),
                    'userid':i.userid,
                    'nickname':i.nickname,
                    'visits':int(i.visits),
                    'thumbup':int(i.thumbup),
                    'share':0,
                    'comment':int(i.comment),
                    'avatar':i.avatar,
                    'collected':i.collected,
                    'hasthumbup':i.hasthumbup,
                    'parent':0
                })
            return JsonResponse({'results': data})
        except Exception as e:
            return JsonResponse({"errmsg":str(e)})


    '''发布吐槽'''
    @loginrequired
    def post(self,request):
            try:
                data = json.loads(request.body)
                content = data['content']
                parent = data.get('parent')
                if parent is not None:
                    parent_spit = Spit.objects.get(id=parent)
                    spit = Spit(
                        content=content,
                        publishtime=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                        userid='1222',
                        nickname='陶昊天',
                        visits=0,
                        thumbup=0,
                        comment=0,
                        avatar=None,
                        collected=False,
                        hasthumbup=False,
                        parent=parent_spit
                    )
                else:
                    spit = Spit(
                        content=content,
                        publishtime=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                        userid='1222',
                        nickname='6666',
                        visits=0,
                        thumbup=0,
                        comment=0,
                        avatar=None,
                        collected=False,
                        hasthumbup=False,
                        parent=None
                    )
                spit.save()
                return JsonResponse({'message':'发布吐槽成功','success':True})
            except Exception as e:
                return JsonResponse({"errmsg":str(e)})


'''收藏和取消吐槽'''
class SpitOutView(View):
    def put(self,request,id):
        try:
            spii = Spit.objects.get(id=id)
            if spii.collected == False:
                spii.collected = True
                # 因为userid是字符串类型，但是他又需要发布人的id，
                # 碰巧发布人的id是mongodb的_id形式就是ObjectId形式，不是字符串所以需要进行转换
                spii.userid = str(ObjectId(id))
                spii.save()
                return JsonResponse({'message':'收藏吐槽成功','success':True})
            else:
                spii.collected = False
                spii.save()
                return JsonResponse({'message':'取消收藏成功','success':False})
        except Exception as e:
            return JsonResponse({"errmsg":str(e)})


'''点赞或取消点赞吐槽'''
class SpitThumbs(View):
    def put(self,request,id):
        try:
            spii = Spit.objects.get(id=id)
            if spii.hasthumbup == False:
                spii.hasthumbup = True
                spii.thumbup += 1
                spii.userid = str(ObjectId(id))
                spii.save()
                return JsonResponse({'message':'喜欢吐槽成功','success':True})
            else:
                spii.hasthumbup = False
                spii.thumbup -= 1
                spii.userid = str(ObjectId(id))
                spii.save()
                return JsonResponse({"message":"取消收藏成功","success":False})
        except Exception as e:
            return JsonResponse({'errmsg':str(e)})


'''点击查看吐槽详情'''
class SpitDetail(View):
    def get(self,request,id):
        try:
            spii = Spit.objects.get(id=id)
            data = {
                'id':str(ObjectId(id)),
                'content':spii.content,
                'publishtime':spii.publishtime,
                'userid':spii.userid,
                'nickname':spii.nickname,
                'visits': spii.visits,
                'thumbup':spii.thumbup,
                'comment':spii.comment,
                'avatar':spii.avatar,
                'collected':spii.collected,
                'hasthumbup':spii.hasthumbup,
                'parent':spii.parent
            }
            return JsonResponse(data)
        except Exception as e:
            return JsonResponse({'errmsg':str(e)})


class SpitComments(View):
    def get(self, request, id):
        try:
            spii = Spit.objects.filter(parent=id).all()
            data_list = []
            for spit in spii:
                data_list.append({
                    'id': str(ObjectId(id)),
                    'content': spit.content,
                    'publishtime': spit.publishtime,
                    'userid': spit.userid,
                    'nickname': spit.nickname,
                    'visits': spit.visits,
                    'thumbup': spit.thumbup,
                    'comment': spit.comment,
                    'avatar': spit.avatar,
                    'collected': spit.collected,
                    'hasthumbup': spit.hasthumbup,
                    'parent': spit.parent
                })
            return JsonResponse(data_list, safe=False)
        except Exception as e:
            return JsonResponse({'errmsg': str(e)})